from cpbox.tool import dockerutil
from cpbox.tool import template

IMAGE_NAME = 'docker.yizhoucp.cn/android-ci/ci:1.0.0'
CONTAINER_NAME = 'cp-android-app'

class Docker:

    def __init__(self, app):
        self.app = app
        self.working_dir = self.app.app_persistent_storage_dir
        self.is_running = None
        self.volumes = {self.working_dir: self.working_dir}

    def ensure_container(self):
        is_running = self.container_is_running()
        if not is_running:
            self.close()
            self.run_container()

    def run_cmd_in_container(self, cmd):
        self.ensure_container()
        mod = dockerutil.fg_mode()
        mod = '-t'
        cmd = 'docker exec %s %s bash -c "%s"' % (mod, CONTAINER_NAME, cmd)
        self.app.shell_run(cmd)

    def container_is_running(self):
        if self.is_running is None:
            self.is_running = self.app.container_is_running(CONTAINER_NAME)
        return self.is_running

    def close(self):
        self.app.remove_container(CONTAINER_NAME, force=True)
        self.is_running = None

    def run_container(self):
        args = dockerutil.base_docker_args(container_name=CONTAINER_NAME, volumes=self.volumes, working_dir=self.working_dir)
        cmd = 'tail -f /dev/null'
        mod = '-d'
        cmd_data = {'args': args, 'image': IMAGE_NAME, 'cmd': cmd, 'mod': mod}

        cmd = template.render_str('docker run {{ mod }} {{ args }} --rm {{ image }} {{ cmd }}', cmd_data)
        self.app.shell_run(cmd)